package com.example.bankingsystemandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TextView;

import com.csc.bankingsystem.core.dto.AccountInfoDTO;
import com.example.bankingsystemandroid.Holder.InfoHolder;
import com.example.bankingsystemandroid.utils.PropertiesConfig;
import com.example.bankingsystemandroid.utils.PropertyManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class InformationFragment extends Fragment {
	private TextView firstNameTextView;
	private TextView midNameTextView;
	private TextView lastNameTextView;
	private TextView phone1stTextView;
	private TextView phone2ndTextView;
	private TextView email1stTextView;
	private TextView email2ndTextView;
	private TableLayout tableView;

	private ArrayList<AccountInfoDTO> listUser = new ArrayList<AccountInfoDTO>();
	private ProgressBar mProgress;

	public InformationFragment() {

		GetUserInfoTask accountInfoTask = new GetUserInfoTask();
		accountInfoTask.execute();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_information,
				container, false);
		setTableView((TableLayout) rootView
				.findViewById(R.id.table_information_fragment));

		mProgress = (ProgressBar) rootView
				.findViewById(R.id.progress_bar_information_fragment);
		mProgress.bringToFront();
		mProgress.setIndeterminate(true);
		mProgress.setVisibility(View.VISIBLE);

		tableView.setVisibility(View.INVISIBLE);
		setFirstNameTextView((TextView) tableView
				.findViewById(R.id.firstName_information_fragment));
		setMidNameTextView((TextView) tableView
				.findViewById(R.id.midName_information_fragment));
		setLastNameTextView((TextView) tableView
				.findViewById(R.id.lastName_information_fragment));
		setEmail1stTextView((TextView) tableView
				.findViewById(R.id.email1st_information_fragment));
		setEmail2ndTextView((TextView) tableView
				.findViewById(R.id.email2nd_information_fragment));
		setPhone1stTextView((TextView) tableView
				.findViewById(R.id.phone1st_information_fragment));
		setPhone2ndTextView((TextView) tableView
				.findViewById(R.id.phone2nd_information_fragment));

		// ----------------------

		return rootView;
	}

	private class GetUserInfoTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			listUser = InfoHolder.getAccountInfoList();
			AccountInfoDTO userInfo = listUser.get(0);
			firstNameTextView.setText(userInfo.getFirstName());
			lastNameTextView.setText(userInfo.getLastName());
			midNameTextView.setText(userInfo.getMidName());
			email1stTextView.setText(userInfo.getEmail1());
			email2ndTextView.setText(userInfo.getEmail2());
			phone1stTextView.setText(userInfo.getPhoneNumber1());
			phone2ndTextView.setText(userInfo.getPhoneNumber2());

			if (mProgress.getVisibility() == View.VISIBLE) {
				mProgress.setVisibility(View.GONE);
			}
			if (tableView.getVisibility() == View.INVISIBLE) {
				tableView.setVisibility(View.VISIBLE);
			}

			super.onPostExecute(result);
		}

		@Override
		protected Void doInBackground(Void... params) {

			/*
			 * Create the POST request
			 */
			String serverIP = PropertiesConfig
					.getProperty(PropertyManager.SERVER_IP);
			String serverPort = PropertiesConfig
					.getProperty(PropertyManager.SERVER_PORT);

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost("http://" + serverIP + ":"
					+ serverPort + "/bankingsystem/api/get-account-info");
			// Request parameters and other properties.

			try {

			} catch (Exception e) {
				// TODO: handle exception
			}
			/*
			 * Execute the HTTP Request
			 */
			try {
				httpPost.addHeader("Cookie",
						"JSESSIONID=" + InfoHolder.getSessionId());
				HttpResponse response = httpClient.execute(httpPost);
				HttpEntity respEntity = response.getEntity();

				if (response != null) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(response.getEntity()
									.getContent(), "UTF-8"));

					StringBuilder builder = new StringBuilder();
					for (String line = null; (line = reader.readLine()) != null;) {
						builder.append(line).append("\n");
					}
					JSONTokener tokener = new JSONTokener(builder.toString());
					JSONArray finalResult = new JSONArray(tokener);

					ArrayList<AccountInfoDTO> accountInfoList = new ArrayList<AccountInfoDTO>();
					Gson gson = new Gson();
					Type collectionType = new TypeToken<ArrayList<AccountInfoDTO>>() {
					}.getType();
					accountInfoList = gson.fromJson(finalResult.toString(),
							collectionType);
					InfoHolder.setAccountInfoList(accountInfoList);
				}
			} catch (ClientProtocolException e) {
				// writing exception to log
				e.printStackTrace();
			} catch (IOException e) {
				// writing exception to log
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}

	public TextView getFirstNameTextView() {
		return firstNameTextView;
	}

	public void setFirstNameTextView(TextView firstNameTextView) {
		this.firstNameTextView = firstNameTextView;
	}

	public TextView getMidNameTextView() {
		return midNameTextView;
	}

	public void setMidNameTextView(TextView midNameTextView) {
		this.midNameTextView = midNameTextView;
	}

	public TextView getLastNameTextView() {
		return lastNameTextView;
	}

	public void setLastNameTextView(TextView lastNameTextView) {
		this.lastNameTextView = lastNameTextView;
	}

	public TextView getPhone1stTextView() {
		return phone1stTextView;
	}

	public void setPhone1stTextView(TextView phone1stTextView) {
		this.phone1stTextView = phone1stTextView;
	}

	public TextView getPhone2ndTextView() {
		return phone2ndTextView;
	}

	public void setPhone2ndTextView(TextView phone2ndTextView) {
		this.phone2ndTextView = phone2ndTextView;
	}

	public TextView getEmail1stTextView() {
		return email1stTextView;
	}

	public void setEmail1stTextView(TextView email1stTextView) {
		this.email1stTextView = email1stTextView;
	}

	public TextView getEmail2ndTextView() {
		return email2ndTextView;
	}

	public void setEmail2ndTextView(TextView email2ndTextView) {
		this.email2ndTextView = email2ndTextView;
	}

	public ArrayList<AccountInfoDTO> getListUser() {
		return listUser;
	}

	public void setListUser(ArrayList<AccountInfoDTO> listUser) {
		this.listUser = listUser;
	}

	public TableLayout getTableView() {
		return tableView;
	}

	public void setTableView(TableLayout tableView) {
		this.tableView = tableView;
	}

}
